package com.gin.kotlin.gf2gamecommunity.composable.index

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.gin.kotlin.enums.CommentSort
import com.gin.kotlin.gf2gamecommunity.app.App
import com.gin.kotlin.gf2gamecommunity.app.AvatarImageShow
import com.gin.kotlin.gf2gamecommunity.app.CommentImageShow
import com.gin.kotlin.gf2gamecommunity.app.DefaultCommentSort
import com.gin.kotlin.gf2gamecommunity.app.TopicImageShow
import com.gin.kotlin.gf2gamecommunity.base.composable.BorderCard
import com.gin.kotlin.gf2gamecommunity.base.composable.ConfirmDialog
import com.gin.kotlin.gf2gamecommunity.base.composable.DropdownMenuSelector
import com.gin.kotlin.gf2gamecommunity.base.composable.TabInfo
import com.gin.kotlin.gf2gamecommunity.base.composable.TabRowPager
import com.gin.kotlin.gf2gamecommunity.base.enums.ImageShow
import com.gin.kotlin.gf2gamecommunity.base.util.SIMPLE_DATE_TIME_FORMATTER
import com.gin.kotlin.gf2gamecommunity.base.util.downloadManager
import com.gin.kotlin.gf2gamecommunity.base.util.enqueue
import com.gin.kotlin.gf2gamecommunity.network.gitee.response.AppRelease
import com.gin.kotlin.gf2gamecommunity.viewmodel.GiteeViewModel
import java.time.ZoneId

@Composable
fun IndexSettings(modifier: Modifier = Modifier) {
    TabRowPager(tabList = listOf(
        TabInfo("行为") { Behavior() },
        TabInfo("版本更新") { VersionUpgrade() },
    ), scrollable = true)
}

/**
 * 版本更新
 * @param modifier Modifier
 */
@Composable
private fun VersionUpgrade(viewModel: GiteeViewModel = viewModel(), modifier: Modifier = Modifier) {
    val state = viewModel.releases.fetch().observeAsState()
    var selectedRelease by remember { mutableStateOf<AppRelease?>(null) }

    state.value?.also { list ->
        LazyColumn(verticalArrangement = Arrangement.spacedBy(2.dp), contentPadding = PaddingValues(8.dp)) {
            items(items = list) { ReleaseCard(it) { r -> selectedRelease = r } }
        }
    } ?: Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
        CircularProgressIndicator()
    }

    selectedRelease?.apply {
        // 相对路径
        val relativePath = obtainFilename() ?: return@apply
        val downloadManager = LocalContext.current.downloadManager
        ConfirmDialog(
            onDismissRequest = { selectedRelease = null },
            onConfirmation = {
                obtainUrl()?.also { url ->
                    downloadManager.enqueue(url, relativePath)
                    App.toast("开始下载")
                    selectedRelease = null
                }
            },
        ) {
            Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
                Text("即将下载版本：")
                Text(tagName, fontSize = 24.sp, fontWeight = FontWeight.Bold)

                Text("(从通知栏查看下载进度)")
            }
        }
    }
}

@Composable
private fun ReleaseCard(appRelease: AppRelease, modifier: Modifier = Modifier, onClickCard: (AppRelease) -> Unit) {
    appRelease.apply {
        BorderCard(modifier = Modifier.clickable { onClickCard(this) }) {
            Column(verticalArrangement = Arrangement.spacedBy(2.dp), modifier = Modifier.padding(8.dp)) {
                Text(tagName, fontSize = 24.sp, fontWeight = FontWeight.Bold)
                Text(body, modifier = Modifier
                    .fillMaxWidth()
                    .graphicsLayer { alpha = 0.7f })
                Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) {
                    Text(createdAt.withZoneSameInstant(ZoneId.systemDefault()).format(SIMPLE_DATE_TIME_FORMATTER))
                    if (preRelease) Text("[预览版]")
                }
            }

        }
    }
}

/**
 * 行为配置
 * @param modifier Modifier
 */
@Composable
private fun Behavior(modifier: Modifier = Modifier) {
    Column(modifier = modifier.padding(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
        Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
            Text("回复排序方式")
            DefaultCommentSort { v, update ->
                DropdownMenuSelector(
                    list = CommentSort.entries.toList(),
                    initValue = v,
                    onSelected = { update(it) },
                    toText = { it!!.des },
                )
            }
        }

        Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
            Text("图片显示策略", fontSize = 22.sp, fontWeight = FontWeight.Bold)
            Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
                Text("主题镇楼")
                TopicImageShow { v, update -> ImageShowSelector(initValue = v, onSelected = { update(it) }) }
            }
            Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
                Text("回复正文")
                CommentImageShow { v, update -> ImageShowSelector(initValue = v, onSelected = { update(it) }) }
            }
            Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
                Text("用户头像")
                AvatarImageShow { v, update -> ImageShowSelector(initValue = v, onSelected = { update(it) }) }
            }
        }
    }
}

/**
 * 图片策略选择器
 * @param initValue ImageShow
 * @param onSelected (item: ImageShow) -> Unit
 */
@Composable
private fun ImageShowSelector(initValue: ImageShow, onSelected: (item: ImageShow) -> Unit) = DropdownMenuSelector(
    list = ImageShow.entries.toList(),
    initValue = initValue,
    onSelected = onSelected,
    toText = { it!!.des },
)